<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1">
<title>Example Code - The Java EE 5 Tutorial</title>
<meta name="robots" content="index,follow">
<meta name="robots" content="index,follow">
<meta name="date" content="2008-10-01">
<link rel="stylesheet" type="text/css" href="css/default.css">
<link rel="stylesheet" type="text/css" href="css/ipg.css">
<link rel="stylesheet" type="text/css" href="css/j5eetutorial.css">
</head>

<body>

<table border="0" cellpadding="5" cellspacing="0" width="100%">
<tbody>
   <tr valign="top">
      <td><p class="toc level1"><a href="docinfo.html">Document Information</a></p>
<p class="toc level1 tocsp"><a href="gexaf.html">Preface</a></p>
<p class="toc level1 tocsp"><a href="gfirp.html">Part&nbsp;I&nbsp;Introduction</a></p>
<p class="toc level2"><a href="bnaaw.html">1.&nbsp;&nbsp;Overview</a></p>
<p class="toc level2"><a href="gfiud.html">2.&nbsp;&nbsp;Using the Tutorial Examples</a></p>
<p class="toc level1 tocsp"><a href="bnadp.html">Part&nbsp;II&nbsp;The Web Tier</a></p>
<p class="toc level2"><a href="bnadr.html">3.&nbsp;&nbsp;Getting Started with Web Applications</a></p>
<p class="toc level2"><a href="bnafd.html">4.&nbsp;&nbsp;Java Servlet Technology</a></p>
<p class="toc level2"><a href="bnagx.html">5.&nbsp;&nbsp;JavaServer Pages Technology</a></p>
<p class="toc level2"><a href="bnajo.html">6.&nbsp;&nbsp;JavaServer Pages Documents</a></p>
<p class="toc level2"><a href="bnakc.html">7.&nbsp;&nbsp;JavaServer Pages Standard Tag Library</a></p>
<p class="toc level2"><a href="bnalj.html">8.&nbsp;&nbsp;Custom Tags in JSP Pages</a></p>
<p class="toc level2"><a href="bnaon.html">9.&nbsp;&nbsp;Scripting in JSP Pages</a></p>
<p class="toc level2"><a href="bnaph.html">10.&nbsp;&nbsp;JavaServer Faces Technology</a></p>
<p class="toc level2"><a href="bnaqz.html">11.&nbsp;&nbsp;Using JavaServer Faces Technology in JSP Pages</a></p>
<p class="toc level2"><a href="bnatx.html">12.&nbsp;&nbsp;Developing with JavaServer Faces Technology</a></p>
<p class="toc level2"><a href="bnavg.html">13.&nbsp;&nbsp;Creating Custom UI Components</a></p>
<p class="toc level2"><a href="bnawo.html">14.&nbsp;&nbsp;Configuring JavaServer Faces Applications</a></p>
<p class="toc level2"><a href="bnaxu.html">15.&nbsp;&nbsp;Internationalizing and Localizing Web Applications</a></p>
<p class="toc level1 tocsp"><a href="bnayk.html">Part&nbsp;III&nbsp;Web Services</a></p>
<p class="toc level2"><a href="bnayl.html">16.&nbsp;&nbsp;Building Web Services with JAX-WS</a></p>
<p class="toc level2"><a href="bnazf.html">17.&nbsp;&nbsp;Binding between XML Schema and Java Classes</a></p>
<p class="toc level2"><a href="bnbdv.html">18.&nbsp;&nbsp;Streaming API for XML</a></p>
<p class="toc level3"><a href="bnbdw.html">Why StAX?</a></p>
<p class="toc level4"><a href="bnbdw.html#bnbdx">Streaming versus DOM</a></p>
<p class="toc level4"><a href="bnbdw.html#bnbdy">Pull Parsing versus Push Parsing</a></p>
<p class="toc level4"><a href="bnbdw.html#bnbdz">StAX Use Cases</a></p>
<p class="toc level4"><a href="bnbdw.html#bnbea">Comparing StAX to Other JAXP APIs</a></p>
<p class="toc level3 tocsp"><a href="bnbec.html">StAX API</a></p>
<p class="toc level4"><a href="bnbec.html#bnbed">Cursor API</a></p>
<p class="toc level4"><a href="bnbec.html#bnbee">Iterator API</a></p>
<p class="toc level5"><a href="bnbec.html#bnbef">Iterator Event Types</a></p>
<p class="toc level5"><a href="bnbec.html#bnbeh">Example of Event Mapping</a></p>
<p class="toc level4 tocsp"><a href="bnbec.html#bnbej">Choosing between Cursor and Iterator APIs</a></p>
<p class="toc level5"><a href="bnbec.html#bnbek">Development Goals</a></p>
<p class="toc level5"><a href="bnbec.html#bnbel">Comparing Cursor and Iterator APIs</a></p>
<p class="toc level3 tocsp"><a href="bnbem.html">Using StAX</a></p>
<p class="toc level4"><a href="bnbem.html#bnben">StAX Factory Classes</a></p>
<p class="toc level5"><a href="bnbem.html#bnbeo"><tt>XMLInputFactory</tt> Class</a></p>
<p class="toc level5"><a href="bnbem.html#bnbeq"><tt>XMLOutputFactory</tt> Class</a></p>
<p class="toc level5"><a href="bnbem.html#bnber"><tt>XMLEventFactory</tt> Class</a></p>
<p class="toc level4 tocsp"><a href="bnbem.html#bnbes">Resources, Namespaces, and Errors</a></p>
<p class="toc level5"><a href="bnbem.html#bnbet">Resource Resolution</a></p>
<p class="toc level5"><a href="bnbem.html#bnbeu">Attributes and Namespaces</a></p>
<p class="toc level5"><a href="bnbem.html#bnbev">Error Reporting and Exception Handling</a></p>
<p class="toc level4 tocsp"><a href="bnbem.html#bnbew">Reading XML Streams</a></p>
<p class="toc level5"><a href="bnbem.html#bnbex">Using <tt>XMLStreamReader</tt></a></p>
<p class="toc level5"><a href="bnbem.html#bnbfb">Using <tt>XMLEventReader</tt></a></p>
<p class="toc level4 tocsp"><a href="bnbem.html#bnbfe">Writing XML Streams</a></p>
<p class="toc level5"><a href="bnbem.html#bnbff">Using <tt>XMLStreamWriter</tt></a></p>
<p class="toc level5"><a href="bnbem.html#bnbfg">Using <tt>XMLEventWriter</tt></a></p>
<p class="toc level3 tocsp"><a href="bnbfi.html">Sun's Streaming XML Parser Implementation</a></p>
<p class="toc level4"><a href="bnbfi.html#bnbfj">Reporting CDATA Events</a></p>
<p class="toc level4"><a href="bnbfi.html#bnbfk">Streaming XML Parser Factories Implementation</a></p>
<div class="onpage">
<p class="toc level3 tocsp"><a href="">Example Code</a></p>
<p class="toc level4"><a href="#bnbfm">Example Code Organization</a></p>
<p class="toc level4"><a href="#bnbfn">Example XML Document</a></p>
<p class="toc level4"><a href="#bnbfo">Cursor Example</a></p>
<p class="toc level5"><a href="#bnbfp">Stepping through Events</a></p>
<p class="toc level5"><a href="#bnbfq">Returning String Representations</a></p>
<p class="toc level5"><a href="#bnbfr">Building and Running the Cursor Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="#bnbfs">Building and Running the Cursor Example Using Ant</a></p>
<p class="toc level4 tocsp"><a href="#bnbft">Cursor-to-Event Example</a></p>
<p class="toc level5"><a href="#bnbfu">Instantiating an <tt>XMLEventAllocator</tt></a></p>
<p class="toc level5"><a href="#bnbfv">Creating an Event Iterator</a></p>
<p class="toc level5"><a href="#bnbfw">Creating the Allocator Method</a></p>
<p class="toc level5"><a href="#bnbfx">Building and Running the Cursor-to-Event Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="#bnbfy">Building and Running the Cursor-to-Event Example Using Ant</a></p>
<p class="toc level4 tocsp"><a href="#bnbfz">Event Example</a></p>
<p class="toc level5"><a href="#bnbga">Creating an Input Factory</a></p>
<p class="toc level5"><a href="#bnbgb">Creating an Event Reader</a></p>
<p class="toc level5"><a href="#bnbgc">Creating an Event Iterator</a></p>
<p class="toc level5"><a href="#bnbgd">Getting the Event Stream</a></p>
<p class="toc level5"><a href="#bnbge">Returning the Output</a></p>
<p class="toc level5"><a href="#bnbgf">Building and Running the Event Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="#bnbgg">Building and Running the Event Example Using Ant</a></p>
<p class="toc level4 tocsp"><a href="#bnbgh">Filter Example</a></p>
<p class="toc level5"><a href="#bnbgi">Implementing the <tt>StreamFilter</tt> Class</a></p>
<p class="toc level5"><a href="#bnbgj">Creating an Input Factory</a></p>
<p class="toc level5"><a href="#bnbgk">Creating the Filter</a></p>
<p class="toc level5"><a href="#bnbgl">Capturing the Event Stream</a></p>
<p class="toc level5"><a href="#bnbgm">Filtering the Stream</a></p>
<p class="toc level5"><a href="#bnbgn">Returning the Output</a></p>
<p class="toc level5"><a href="#bnbgo">Building and Running the Filter Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="#bnbgp">Building and Running the Filter Example Using Ant</a></p>
<p class="toc level4 tocsp"><a href="#bnbgq">Read-and-Write Example</a></p>
<p class="toc level5"><a href="#bnbgr">Creating an Event Producer/Consumer</a></p>
<p class="toc level5"><a href="#bnbgs">Creating an Iterator</a></p>
<p class="toc level5"><a href="#bnbgt">Creating a Writer</a></p>
<p class="toc level5"><a href="#bnbgu">Returning the Output</a></p>
<p class="toc level5"><a href="#bnbgv">Building and Running the Read-and-Write Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="#bnbgw">Building and Running the Read-and-Write Example Using Ant</a></p>
<p class="toc level4 tocsp"><a href="#bnbgx">Writer Example</a></p>
<p class="toc level5"><a href="#bnbgy">Creating the Output Factory</a></p>
<p class="toc level5"><a href="#bnbgz">Creating a Stream Writer</a></p>
<p class="toc level5"><a href="#bnbha">Writing the Stream</a></p>
<p class="toc level5"><a href="#bnbhb">Returning the Output</a></p>
<p class="toc level5"><a href="#bnbhc">Building and Running the Writer Example Using NetBeans IDE</a></p>
<p class="toc level5"><a href="#bnbhd">Building and Running the Writer Example Using Ant</a></p>
</div>
<p class="toc level3 tocsp"><a href="bnbhe.html">Further Information about StAX</a></p>
<p class="toc level2 tocsp"><a href="bnbhf.html">19.&nbsp;&nbsp;SOAP with Attachments API for Java</a></p>
<p class="toc level1 tocsp"><a href="bnblr.html">Part&nbsp;IV&nbsp;Enterprise Beans</a></p>
<p class="toc level2"><a href="bnbls.html">20.&nbsp;&nbsp;Enterprise Beans</a></p>
<p class="toc level2"><a href="bnbnb.html">21.&nbsp;&nbsp;Getting Started with Enterprise Beans</a></p>
<p class="toc level2"><a href="bnboc.html">22.&nbsp;&nbsp;Session Bean Examples</a></p>
<p class="toc level2"><a href="bnbpk.html">23.&nbsp;&nbsp;A Message-Driven Bean Example</a></p>
<p class="toc level1 tocsp"><a href="bnbpy.html">Part&nbsp;V&nbsp;Persistence</a></p>
<p class="toc level2"><a href="bnbpz.html">24.&nbsp;&nbsp;Introduction to the Java Persistence API</a></p>
<p class="toc level2"><a href="bnbrl.html">25.&nbsp;&nbsp;Persistence in the Web Tier</a></p>
<p class="toc level2"><a href="bnbrs.html">26.&nbsp;&nbsp;Persistence in the EJB Tier</a></p>
<p class="toc level2"><a href="bnbtg.html">27.&nbsp;&nbsp;The Java Persistence Query Language</a></p>
<p class="toc level1 tocsp"><a href="bnbwi.html">Part&nbsp;VI&nbsp;Services</a></p>
<p class="toc level2"><a href="bnbwj.html">28.&nbsp;&nbsp;Introduction to Security in the Java EE Platform</a></p>
<p class="toc level2"><a href="bnbyk.html">29.&nbsp;&nbsp;Securing Java EE Applications</a></p>
<p class="toc level2"><a href="bncas.html">30.&nbsp;&nbsp;Securing Web Applications</a></p>
<p class="toc level2"><a href="bncdq.html">31.&nbsp;&nbsp;The Java Message Service API</a></p>
<p class="toc level2"><a href="bncgv.html">32.&nbsp;&nbsp;Java EE Examples Using the JMS API</a></p>
<p class="toc level2"><a href="bncih.html">33.&nbsp;&nbsp;Transactions</a></p>
<p class="toc level2"><a href="bncjh.html">34.&nbsp;&nbsp;Resource Connections</a></p>
<p class="toc level2"><a href="bncjx.html">35.&nbsp;&nbsp;Connector Architecture</a></p>
<p class="toc level1 tocsp"><a href="bnckn.html">Part&nbsp;VII&nbsp;Case Studies</a></p>
<p class="toc level2"><a href="bncko.html">36.&nbsp;&nbsp;The Coffee Break Application</a></p>
<p class="toc level2"><a href="bnclz.html">37.&nbsp;&nbsp;The Duke's Bank Application</a></p>
<p class="toc level1 tocsp"><a href="gexbq.html">Part&nbsp;VIII&nbsp;Appendixes</a></p>
<p class="toc level2"><a href="bncno.html">A.&nbsp;&nbsp;Java Encoding Schemes</a></p>
<p class="toc level2"><a href="bncnq.html">B.&nbsp;&nbsp;Preparation for Java EE Certification Exams</a></p>
<p class="toc level2"><a href="bncnt.html">C.&nbsp;&nbsp;About the Authors</a></p>
<p class="toc level1 tocsp"><a href="idx-1.html">Index</a></p>
</td>
      <td width="10px">&nbsp;</td>
      <td width="705px">
         <div class="header">
             <div class="header-links-top">
                 <a href="http://java.sun.com">java.sun.com</a> |
                 <a href="http://docs.sun.com/">docs.sun.com</a><br>
             </div> 
             <img src="graphics/tutorialBanner.gif" width="704" height="120" alt="The Java&trade; EE 5 Tutorial"/>
             <div class="header-links">
	         <a href="index.html">Home</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/download.html">Download</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/JavaEETutorial.pdf">PDF</a> |
                 <a href="http://java.sun.com/javaee/5/docs/api/index.html">API</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/faq.html">FAQ</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/search.html">Search</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/sendusmail.html">Feedback</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/history.html">History</a>
             </div>
             <div class="navigation">
                 <a href="bnbfi.html"><img style="padding-right: 3px" src="graphics/leftButton.gif" border="0"></a>
                 <a href="sjsaseej2eet.html"><img style="padding-right: 3px" src="graphics/upButton.gif" border="0"></a>
                 <a href="bnbhe.html"><img style="padding-left: 3px" src="graphics/rightButton.gif" border="0"></a>
             </div>
         </div>

	 <div class="maincontent">      	 
             

<a name="bnbfl"></a><h3>Example Code</h3>
<a name="indexterm-1872"></a><a name="indexterm-1873"></a><p>This section steps through the example StAX code included in the Java EE
5 Tutorial bundle. All example directories used in this section are located in
the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/</tt> directory.</p><p>The topics covered in this section are as follows:</p>
<ul><li><p><a href="#bnbfm">Example Code Organization</a></p></li>
<li><p><a href="#bnbfn">Example XML Document</a></p></li>
<li><p><a href="#bnbfo">Cursor Example</a></p></li>
<li><p><a href="#bnbft">Cursor-to-Event Example</a></p></li>
<li><p><a href="#bnbfz">Event Example</a></p></li>
<li><p><a href="#bnbgh">Filter Example</a></p></li>
<li><p><a href="#bnbgq">Read-and-Write Example</a></p></li>
<li><p><a href="#bnbgx">Writer Example</a></p></li></ul>


<a name="bnbfm"></a><h4>Example Code Organization</h4>
<p>The <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/</tt> directory contains the six StAX example directories:</p>
<ul><li><p><b>Cursor example</b>: The <tt>cursor</tt> directory contains <tt>CursorParse.java</tt>, which illustrates how to use the <tt>XMLStreamReader</tt> (cursor) API to read an XML file.</p></li>
<li><p><b>Cursor-to-Event example</b>: The <tt>cursor2event</tt> directory contains <tt>CursorApproachEventObject.java</tt>, which illustrates how an application can get information as an <tt>XMLEvent</tt> object when using cursor API.</p></li>
<li><p><b>Event example</b>: The <tt>event</tt> directory contains <tt>EventParse.java</tt>, which illustrates how to use the <tt>XMLEventReader</tt> (event iterator) API to read an XML file.</p></li>
<li><p><b>Filter example</b>: The <tt>filter</tt> directory contains <tt>MyStreamFilter.java</tt>, which illustrates how to use the StAX Stream Filter APIs. In this example, the filter accepts only <tt>StartElement</tt> and <tt>EndElement</tt> events, and filters out the remainder of the events.</p></li>
<li><p><b>Read-and-Write example</b>: The <tt>readnwrite</tt> directory contains <tt>EventProducerConsumer.java</tt>, which illustrates how the StAX producer/consumer mechanism can be used to simultaneously read and write XML streams.</p></li>
<li><p><b>Writer example</b>: The <tt>writer</tt> directory contains <tt>CursorWriter.java</tt>, which illustrates how to use <tt>XMLStreamWriter</tt> to write an XML file programatically.</p></li></ul>
<p>All of the StAX examples except for the Writer example use an
example XML document, <tt>BookCatalog.xml</tt>.</p>

<a name="bnbfn"></a><h4>Example XML Document</h4>
<p>The example XML document, <tt>BookCatalog.xml</tt>, used by most of the StAX example classes,
is a simple book catalog based on the common <tt>BookCatalogue</tt> namespace. The contents
of <tt>BookCatalog.xml</tt> are listed below:</p><pre>&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;BookCatalogue xmlns="http://www.publishing.org">
    &lt;Book>
        &lt;Title>Yogasana Vijnana: the Science of Yoga&lt;/Title>
        &lt;author>Dhirendra Brahmachari&lt;/Author>
        &lt;Date>1966&lt;/Date>
        &lt;ISBN>81-40-34319-4&lt;/ISBN>
        &lt;Publisher>Dhirendra Yoga Publications&lt;/Publisher>
        &lt;Cost currency="INR">11.50&lt;/Cost>
    &lt;/Book>
    &lt;Book>
        &lt;Title>The First and Last Freedom&lt;/Title>
        &lt;Author>J. Krishnamurti&lt;/Author>
        &lt;Date>1954&lt;/Date>
        &lt;ISBN>0-06-064831-7&lt;/ISBN>
        &lt;Publisher>Harper &amp;amp; Row&lt;/Publisher>
        &lt;Cost currency="USD">2.95&lt;/Cost>
    &lt;/Book>
&lt;/BookCatalogue></pre>

<a name="bnbfo"></a><h4>Cursor Example</h4>
<a name="indexterm-1874"></a><a name="indexterm-1875"></a><p>Located in the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/cursor/</tt> directory, <tt>CursorParse.java</tt> demonstrates using the StAX cursor API to
read an XML document. In the Cursor example, the application instructs the parser
to read the next event in the XML input stream by calling <tt>&lt;code>next()&lt;/code></tt>.</p><p>Note that <tt>&lt;code>next()&lt;/code></tt> just returns an integer constant corresponding to underlying event where
the parser is positioned. The application needs to call the relevant function to
get more information related to the underlying event.</p><p>You can imagine this approach as a virtual cursor moving across the XML
input stream. There are various accessor methods which can be called when that
virtual cursor is at a particular event.</p>

<a name="bnbfp"></a><h5>Stepping through Events</h5>
<p>In this example, the client application pulls the next event in the XML
stream by calling the <tt>next</tt> method on the parser; for example:</p><pre>try {
    for (int i = 0 ; i &lt; count ; i++) {
        // pass the file name.. all relative entity
        // references will be resolved against this as
        // base URI.
        XMLStreamReader xmlr =
            xmlif.createXMLStreamReader(filename,
                new FileInputStream(filename));
        // when XMLStreamReader is created, it is positioned
        // at START_DOCUMENT event.
        int eventType = xmlr.getEventType();
        printEventType(eventType);
        printStartDocument(xmlr);
        // check if there are more events in the input stream
        while(xmlr.hasNext()) {
            eventType = xmlr.next();
            printEventType(eventType);
            // these functions print the information about
            // the particular event by calling the relevant
            // function
            printStartElement(xmlr);
            printEndElement(xmlr);
            printText(xmlr);
            printPIData(xmlr);
            printComment(xmlr);
        }
    }
}</pre><p>Note that <tt>next</tt> just returns an integer constant corresponding to the event underlying
the current cursor location. The application calls the relevant function to get more
information related to the underlying event. There are various accessor methods which can
be called when the cursor is at particular event.</p>

<a name="bnbfq"></a><h5>Returning String Representations</h5>
<p>Because the <tt>next</tt> method only returns integers corresponding to underlying event types, you
typically need to map these integers to string representations of the events; for
example:</p><pre>public final static String getEventTypeString(int eventType) {
    switch (eventType) {
        case XMLEvent.START_ELEMENT:
            return "START_ELEMENT";
        case XMLEvent.END_ELEMENT:
            return "END_ELEMENT";
        case XMLEvent.PROCESSING_INSTRUCTION:
            return "PROCESSING_INSTRUCTION";
        case XMLEvent.CHARACTERS:
            return "CHARACTERS";
        case XMLEvent.COMMENT:
            return "COMMENT";
        case XMLEvent.START_DOCUMENT:
            return "START_DOCUMENT";
        case XMLEvent.END_DOCUMENT:
            return "END_DOCUMENT";
        case XMLEvent.ENTITY_REFERENCE:
            return "ENTITY_REFERENCE";
        case XMLEvent.ATTRIBUTE:
            return "ATTRIBUTE";
        case XMLEvent.DTD:
            return "DTD";
        case XMLEvent.CDATA:
            return "CDATA";
        case XMLEvent.SPACE:
            return "SPACE";
    }
    return "UNKNOWN_EVENT_TYPE , " + eventType;
}</pre>

<a name="bnbfr"></a><h5>Building and Running the Cursor Example Using NetBeans IDE</h5>
<p>Follow these instructions to build and run the Cursor example on your Application
Server instance using the NetBeans IDE.</p>
<ol><li><p>In NetBeans IDE, select File&rarr;Open Project.</p></li>
<li><p>In the Open Project dialog, navigate to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/</tt> directory.</p></li>
<li><p>Select the <tt>cursor</tt> folder.</p></li>
<li><p>Select the Open as Main Project check box.</p></li>
<li><p>Click Open Project.</p></li>
<li><p>In the Projects tab, right-click the <tt>cursor</tt> project and select Properties. The Project Properties dialog is displayed.</p></li>
<li><p>Enter the following in the Arguments field:</p><pre><tt><b>-x 1 BookCatalog.xml</b></tt></pre></li>
<li><p>Click OK.</p></li>
<li><p>Right-click the <tt>cursor</tt> project and select Run.</p></li></ol>


<a name="bnbfs"></a><h5>Building and Running the Cursor Example Using Ant</h5>
<p>To compile and run the Cursor example using Ant, in a terminal
window, go to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/cursor/</tt> directory and type the following:</p><pre><tt><b>ant run-cursor</b></tt></pre>

<a name="bnbft"></a><h4>Cursor-to-Event Example</h4>
<a name="indexterm-1876"></a><a name="indexterm-1877"></a><p>Located in the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/cursor2event/</tt> directory, <tt>CursorApproachEventObject.java</tt> demonstrates how to get information returned by
an <tt>XMLEvent</tt> object even when using the cursor API.</p><p>The idea here is that the cursor API&rsquo;s <tt>XMLStreamReader</tt> returns integer constants corresponding
to particular events, while the event iterator API&rsquo;s <tt>XMLEventReader</tt> returns immutable and persistent event
objects. <tt>XMLStreamReader</tt> is more efficient, but <tt>XMLEventReader</tt> is easier to use, because
all the information related to a particular event is encapsulated in a returned
<tt>XMLEvent</tt> object. However, the disadvantage of event approach is the extra overhead of
creating objects for every event, which consumes both time and memory.</p><p>With this mind, <tt>XMLEventAllocator</tt> can be used to get event information as an
<tt>XMLEvent</tt> object, even when using the cursor API.</p>

<a name="bnbfu"></a><h5>Instantiating an <tt>XMLEventAllocator</tt></h5>
<a name="indexterm-1878"></a><p>The first step is to create a new <tt>XMLInputFactory</tt> and instantiate an <tt>XMLEventAllocator</tt>:</p><pre>XMLInputFactory xmlif = XMLInputFactory.newInstance();
System.out.println("FACTORY: " + xmlif);
xmlif.setEventAllocator(new XMLEventAllocatorImpl());
allocator = xmlif.getEventAllocator();
XMLStreamReader xmlr = xmlif.createXMLStreamReader(filename,
    new FileInputStream(filename));</pre>

<a name="bnbfv"></a><h5>Creating an Event Iterator</h5>
<p>The next step is to create an event iterator:</p><pre>int eventType = xmlr.getEventType();
while(xmlr.hasNext()){
    eventType = xmlr.next();
    //Get all "Book" elements as XMLEvent object
    if(eventType == XMLStreamConstants.START_ELEMENT &amp;&amp;
        xmlr.getLocalName().equals("Book")){
        //get immutable XMLEvent
        StartElement event = getXMLEvent(xmlr).asStartElement();
        System.out.println("EVENT: " + event.toString());
    }
}</pre>

<a name="bnbfw"></a><h5>Creating the Allocator Method</h5>
<p>The final step is to create the <tt>XMLEventAllocator</tt> method:</p><pre>private static XMLEvent getXMLEvent(XMLStreamReader reader)
         throws XMLStreamException {
    return allocator.allocate(reader);
}</pre>

<a name="bnbfx"></a><h5>Building and Running the Cursor-to-Event Example Using NetBeans IDE</h5>
<p>Follow these instructions to build and run the Cursor-to-Event example on your Application
Server instance using the NetBeans IDE.</p>
<ol><li><p>In NetBeans IDE, select File&rarr;Open Project.</p></li>
<li><p>In the Open Project dialog, navigate to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/</tt> directory.</p></li>
<li><p>Select the <tt>cursor2event</tt> folder.</p></li>
<li><p>Select the Open as Main Project check box.</p></li>
<li><p>Click Open Project.</p></li>
<li><p>In the Projects tab, right-click the <tt>cursor2event</tt> project and select Properties. The Project Properties dialog is displayed.</p></li>
<li><p>Enter the following in the Arguments field:</p><pre><tt><b>BookCatalog.xml</b></tt></pre></li>
<li><p>Click OK.</p></li>
<li><p>Right-click the <tt>cursor2event</tt> project and select Run.</p><p>Note how the <tt>Book</tt> events are returned as strings.</p></li></ol>


<a name="bnbfy"></a><h5>Building and Running the Cursor-to-Event Example Using Ant</h5>
<p>To compile and run the Cursor-to-Event example using Ant, in a terminal window,
go to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/cursor2event/</tt> directory and type the following:</p><pre><tt><b>ant run-cursor2event</b></tt></pre>

<a name="bnbfz"></a><h4>Event Example</h4>
<a name="indexterm-1879"></a><a name="indexterm-1880"></a><p>Located in the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/event/</tt> directory, <tt>EventParse.java</tt> demonstrates how to use the StAX
event API to read an XML document.</p>

<a name="bnbga"></a><h5>Creating an Input Factory</h5>
<p>The first step is to create a new instance of <tt>XMLInputFactory</tt>:</p><pre>XMLInputFactory factory = XMLInputFactory.newInstance();
System.out.println("FACTORY: " + factory);</pre>

<a name="bnbgb"></a><h5>Creating an Event Reader</h5>
<p>The next step is to create an instance of <tt>XMLEventReader</tt>:</p><pre>XMLEventReader r = factory.createXMLEventReader(filename,
     new FileInputStream(filename));</pre>

<a name="bnbgc"></a><h5>Creating an Event Iterator</h5>
<p>The third step is to create an event iterator:</p><pre>XMLEventReader r = factory.createXMLEventReader(filename,
     new FileInputStream(filename));
while(r.hasNext()) {
    XMLEvent e = r.nextEvent();
    System.out.println(e.toString());
}</pre>

<a name="bnbgd"></a><h5>Getting the Event Stream</h5>
<p>The final step is to get the underlying event stream:</p><pre>public final static String getEventTypeString(int eventType) {
    switch (eventType) {
        case XMLEvent.START_ELEMENT:
            return "START_ELEMENT";
        case XMLEvent.END_ELEMENT:
            return "END_ELEMENT";
        case XMLEvent.PROCESSING_INSTRUCTION:
            return "PROCESSING_INSTRUCTION";
        case XMLEvent.CHARACTERS:
            return "CHARACTERS";
        case XMLEvent.COMMENT:
            return "COMMENT";
        case XMLEvent.START_DOCUMENT:
            return "START_DOCUMENT";
        case XMLEvent.END_DOCUMENT:
            return "END_DOCUMENT";
        case XMLEvent.ENTITY_REFERENCE:
            return "ENTITY_REFERENCE";
        case XMLEvent.ATTRIBUTE:
            return "ATTRIBUTE";
        case XMLEvent.DTD:
            return "DTD";
        case XMLEvent.CDATA:
            return "CDATA";
        case XMLEvent.SPACE:
            return "SPACE";
    }
    return "UNKNOWN_EVENT_TYPE " + "," + eventType;
}</pre>

<a name="bnbge"></a><h5>Returning the Output</h5>
<p>When you run the Event example, the <tt>EventParse</tt> class is compiled, and the
XML stream is parsed as events and returned to <tt>STDOUT</tt>. For example,
an instance of the <tt>Author</tt> element is returned as:</p><pre>&lt;[&rsquo;http://www.publishing.org&rsquo;]::Author>
    Dhirendra Brahmachari
&lt;/[&rsquo;http://www.publishing.org&rsquo;]::Author></pre><p>Note in this example that the event comprises an opening and closing tag,
both of which include the namespace. The content of the element is
returned as a string within the tags.</p><p>Similarly, an instance of the <tt>Cost</tt> element is returned as:</p><pre>&lt;[&rsquo;http://www.publishing.org&rsquo;]::Cost currency=&rsquo;INR&rsquo;>
    11.50
&lt;/[&rsquo;http://www.publishing.org&rsquo;]::Cost></pre><p>In this case, the <tt>currency</tt> attribute and value are returned in the opening
tag for the event.</p>

<a name="bnbgf"></a><h5>Building and Running the Event Example Using NetBeans IDE</h5>
<p>Follow these instructions to build and run the Event example on your Application
Server instance using the NetBeans IDE.</p>
<ol><li><p>In NetBeans IDE, select File&rarr;Open Project.</p></li>
<li><p>In the Open Project dialog, navigate to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/</tt> directory.</p></li>
<li><p>Select the <tt>event</tt> folder.</p></li>
<li><p>Select the Open as Main Project check box.</p></li>
<li><p>Click Open Project.</p></li>
<li><p>In the Projects tab, right-click the <tt>event</tt> project and select Properties. The Project Properties dialog is displayed.</p></li>
<li><p>Enter the following in the Arguments field:</p><pre><tt><b>BookCatalog.xml</b></tt></pre></li>
<li><p>Click OK.</p></li>
<li><p>Right-click the <tt>event</tt> project and select Run.</p></li></ol>


<a name="bnbgg"></a><h5>Building and Running the Event Example Using Ant</h5>
<p>To compile and run the Event example using Ant, in a terminal
window, go to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/event/</tt> directory and type the following:</p><pre><tt><b>ant run-event</b></tt></pre>

<a name="bnbgh"></a><h4>Filter Example</h4>
<a name="indexterm-1881"></a><a name="indexterm-1882"></a><p>Located in the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/filter/</tt> directory, <tt>MyStreamFilter.java</tt> demonstrates how to use the StAX stream
filter API to filter out events not needed by your application. In this
example, the parser filters out all events except <tt>StartElement</tt> and <tt>EndElement</tt>.</p>

<a name="bnbgi"></a><h5>Implementing the <tt>StreamFilter</tt> Class</h5>
<p>The <tt>MyStreamFilter</tt> class implements <tt>javax.xml.stream.StreamFilter</tt>:</p><pre>public class MyStreamFilter
     implements javax.xml.stream.StreamFilter {</pre>

<a name="bnbgj"></a><h5>Creating an Input Factory</h5>
<p>The next step is to create an instance of <tt>XMLInputFactory</tt>. In this case,
various properties are also set on the factory:</p><pre>XMLInputFactory xmlif = null ;
try {
    xmlif = XMLInputFactory.newInstance();
    xmlif.setProperty(
        XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,
        Boolean.TRUE);
    xmlif.setProperty(
        XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,
        Boolean.FALSE);
    xmlif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE,
        Boolean.TRUE);
    xmlif.setProperty(XMLInputFactory.IS_COALESCING,
        Boolean.TRUE);
} catch (Exception ex) {
    ex.printStackTrace();
}
System.out.println("FACTORY: " + xmlif);
System.out.println("filename = "+ filename);</pre>

<a name="bnbgk"></a><h5>Creating the Filter</h5>
<p>The next step is to instantiate a file input stream and create
the stream filter:</p><pre>FileInputStream fis = new FileInputStream(filename);
                
XMLStreamReader xmlr = xmlif.createFilteredReader(
    xmlif.createXMLStreamReader(fis), new MyStreamFilter());

int eventType = xmlr.getEventType();
printEventType(eventType);
while(xmlr.hasNext()) {
    eventType = xmlr.next();
    printEventType(eventType);
    printName(xmlr,eventType);
    printText(xmlr);
    if (xmlr.isStartElement()) {
        printAttributes(xmlr);
    }
    printPIData(xmlr);
    System.out.println("-----------------------------");
}</pre>

<a name="bnbgl"></a><h5>Capturing the Event Stream</h5>
<p>The next step is to capture the event stream. This is done
in basically the same way as in the Event example.</p>

<a name="bnbgm"></a><h5>Filtering the Stream</h5>
<p>The final step is to filter the stream:</p><pre>public boolean accept(XMLStreamReader reader) {
    if (!reader.isStartElement() &amp;&amp; !reader.isEndElement())
        return false;
    else
        return true;
}</pre>

<a name="bnbgn"></a><h5>Returning the Output</h5>
<p>When you run the Filter example, the <tt>MyStreamFilter</tt> class is compiled, and the
XML stream is parsed as events and returned to <tt>STDOUT</tt>. For example,
an <tt>Author</tt> event is returned as follows:</p><pre>EVENT TYPE(1):START_ELEMENT
HAS NAME: Author
HAS NO TEXT
HAS NO ATTRIBUTES
-----------------------------
EVENT TYPE(2):END_ELEMENT
HAS NAME: Author
HAS NO TEXT
-----------------------------</pre><p>Similarly, a <tt>Cost</tt> event is returned as follows:</p><pre>EVENT TYPE(1):START_ELEMENT
HAS NAME: Cost
HAS NO TEXT

HAS ATTRIBUTES:
 ATTRIBUTE-PREFIX:
 ATTRIBUTE-NAMESP: null
ATTRIBUTE-NAME:   currency
ATTRIBUTE-VALUE: USD
ATTRIBUTE-TYPE:  CDATA

-----------------------------
EVENT TYPE(2):END_ELEMENT
HAS NAME: Cost
HAS NO TEXT
-----------------------------</pre><p>See <a href="bnbec.html#bnbee">Iterator API</a> and <a href="bnbem.html#bnbew">Reading XML Streams</a> for a more detailed discussion of StAX event parsing.</p>

<a name="bnbgo"></a><h5>Building and Running the Filter Example Using NetBeans IDE</h5>
<p>Follow these instructions to build and run the Filter example on your Application
Server instance using the NetBeans IDE.</p>
<ol><li><p>In NetBeans IDE, select File&rarr;Open Project.</p></li>
<li><p>In the Open Project dialog, navigate to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/</tt> directory.</p></li>
<li><p>Select the <tt>filter</tt> folder.</p></li>
<li><p>Select the Open as Main Project check box.</p></li>
<li><p>Click Open Project.</p></li>
<li><p>In the Projects tab, right-click the <tt>filter</tt> project and select Properties. The Project Properties dialog is displayed.</p></li>
<li><p>Enter the following in the Arguments field:</p><pre><tt><b>-f BookCatalog.xml</b></tt></pre></li>
<li><p>Click OK.</p></li>
<li><p>Right-click the <tt>filter</tt> project and select Run.</p></li></ol>


<a name="bnbgp"></a><h5>Building and Running the Filter Example Using Ant</h5>
<p>To compile and run the Filter example using Ant, in a terminal
window, go to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/filter/</tt> directory and type the following:</p><pre><tt><b>ant run-filter</b></tt></pre>

<a name="bnbgq"></a><h4>Read-and-Write Example</h4>
<a name="indexterm-1883"></a><a name="indexterm-1884"></a><p>Located in the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/readnwrite/</tt> directory, <tt>EventProducerConsumer.java</tt> demonstrates how to use a StAX parser
simultaneously as both a producer and a consumer.</p><p>The StAX <tt>XMLEventWriter</tt> API extends from the <tt>XMLEventConsumer</tt> interface, and is referred
to as an <b>event consumer</b>. By contrast, <tt>XMLEventReader</tt> is an <b>event producer</b>. StAX supports simultaneous reading
and writing, such that it is possible to read from one XML stream
sequentially and simultaneously write to another stream.</p><p>The Read-and-Write example shows how the StAX producer/consumer mechanism can be used to
read and write simultaneously. This example also shows how a stream can be
modified and how new events can be added dynamically and then written to
a different stream.</p>

<a name="bnbgr"></a><h5>Creating an Event Producer/Consumer</h5>
<p>The first step is to instantiate an event factory and then create
an instance of an event producer/consumer:</p><pre>XMLEventFactory m_eventFactory = XMLEventFactory.newInstance();
public EventProducerConsumer() {
}
...
try {
    EventProducerConsumer ms = new EventProducerConsumer();
    
    XMLEventReader reader =
        XMLInputFactory.newInstance().createXMLEventReader(
            new java.io.FileInputStream(args[0]));
    XMLEventWriter writer =
        XMLOutputFactory.newInstance().createXMLEventWriter(
            System.out);</pre>

<a name="bnbgs"></a><h5>Creating an Iterator</h5>
<p>The next step is to create an iterator to parse the stream:</p><pre>while(reader.hasNext()) {
    XMLEvent event = (XMLEvent)reader.next();
    if (event.getEventType() == event.CHARACTERS) {
        writer.add(ms.getNewCharactersEvent(event.asCharacters()));
    } else {
        writer.add(event);
    }
}
writer.flush();</pre>

<a name="bnbgt"></a><h5>Creating a Writer</h5>
<p>The final step is to create a stream writer in the form
of a new <tt>Character</tt> event:</p><pre>Characters getNewCharactersEvent(Characters event) {
    if (event.getData().equalsIgnoreCase("Name1")) {
        return m_eventFactory.createCharacters(
            Calendar.getInstance().getTime().toString());
    }
    //else return the same event
    else {
        return event;
    }
}</pre>

<a name="bnbgu"></a><h5>Returning the Output</h5>
<p>When you run the Read-and-Write example, the <tt>EventProducerConsumer</tt> class is compiled, and
the XML stream is parsed as events and written back to <tt>STDOUT</tt>. The
output is the contents of the <tt>BookCatalog.xml</tt> file described in <a href="#bnbfn">Example XML Document</a>.</p>

<a name="bnbgv"></a><h5>Building and Running the Read-and-Write Example Using NetBeans IDE</h5>
<p>Follow these instructions to build and run the Read-and-Write example on your Application
Server instance using the NetBeans IDE.</p>
<ol><li><p>In NetBeans IDE, select File&rarr;Open Project.</p></li>
<li><p>In the Open Project dialog, navigate to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/</tt> directory.</p></li>
<li><p>Select the <tt>readnwrite</tt> folder.</p></li>
<li><p>Select the Open as Main Project check box.</p></li>
<li><p>Click Open Project.</p></li>
<li><p>In the Projects tab, right-click the <tt>readnwrite</tt> project and select Properties. The Project Properties dialog is displayed.</p></li>
<li><p>Enter the following in the Arguments field:</p><pre><tt><b>BookCatalog.xml</b></tt></pre></li>
<li><p>Click OK.</p></li>
<li><p>Right-click the <tt>readnwrite</tt> project and select Run.</p></li></ol>


<a name="bnbgw"></a><h5>Building and Running the Read-and-Write Example Using Ant</h5>
<p>To compile and run the Read-and-Write example using Ant, in a terminal window,
go to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/readnwrite/</tt> directory and type the following:</p><pre><tt><b>ant run-readnwrite</b></tt></pre>

<a name="bnbgx"></a><h4>Writer Example</h4>
<a name="indexterm-1885"></a><a name="indexterm-1886"></a><p>Located in the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/writer/</tt> directory, <tt>CursorWriter.java</tt> demonstrates how to use the StAX cursor
API to write an XML stream.</p>

<a name="bnbgy"></a><h5>Creating the Output Factory</h5>
<p>The first step is to create an instance of <tt>XMLOutputFactory</tt>:</p><pre>XMLOutputFactory xof =  XMLOutputFactory.newInstance();</pre>

<a name="bnbgz"></a><h5>Creating a Stream Writer</h5>
<p>The next step is to create an instance of <tt>XMLStreamWriter</tt>:</p><pre>XMLStreamWriter xtw = null;</pre>

<a name="bnbha"></a><h5>Writing the Stream</h5>
<p>The final step is to write the XML stream. Note that the
stream is flushed and closed after the final <tt>EndDocument</tt> is written:</p><pre>xtw = xof.createXMLStreamWriter(new FileWriter(fileName));
xtw.writeComment("all elements here are explicitly in the HTML namespace");
xtw.writeStartDocument("utf-8","1.0");
xtw.setPrefix("html", "http://www.w3.org/TR/REC-html40");
xtw.writeStartElement("http://www.w3.org/TR/REC-html40","html");
xtw.writeNamespace("html", "http://www.w3.org/TR/REC-html40");
xtw.writeStartElement("http://www.w3.org/TR/REC-html40","head");
xtw.writeStartElement("http://www.w3.org/TR/REC-html40","title");
xtw.writeCharacters("Frobnostication");
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeStartElement("http://www.w3.org/TR/REC-html40","body");
xtw.writeStartElement("http://www.w3.org/TR/REC-html40","p");
xtw.writeCharacters("Moved to");
xtw.writeStartElement("http://www.w3.org/TR/REC-html40","a");
xtw.writeAttribute("href","http://frob.com");
xtw.writeCharacters("here");
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeEndDocument();
xtw.flush();
xtw.close();</pre>

<a name="bnbhb"></a><h5>Returning the Output</h5>
<p>When you run the Writer example, the <tt>CursorWriter</tt> class is compiled, and the
XML stream is parsed as events and written to a file named <tt>dist/CursorWriter-Output</tt>:</p><pre>&lt;!--all elements here are explicitly in the HTML namespace-->
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;html:html xmlns:html="http://www.w3.org/TR/REC-html40">
&lt;html:head>
&lt;html:title>Frobnostication&lt;/html:title>&lt;/html:head>
&lt;html:body>
&lt;html:p>Moved to &lt;html:a href="http://frob.com">here&lt;/html:a>
&lt;/html:p>
&lt;/html:body>
&lt;/html:html></pre><p>In the actual <tt>dist/CursorWriter-Output</tt> file, this stream is written without any line breaks;
the breaks have been added here to make the listing easier to read.
In this example, as with the object stream in the Event example, the
namespace prefix is added to both the opening and closing HTML tags. Adding
this prefix is not required by the StAX specification, but it is good
practice when the final scope of the output stream is not definitively known.</p>

<a name="bnbhc"></a><h5>Building and Running the Writer Example Using NetBeans IDE</h5>
<p>Follow these instructions to build and run the Writer example on your Application
Server instance using the NetBeans IDE.</p>
<ol><li><p>In NetBeans IDE, select File&rarr;Open Project.</p></li>
<li><p>In the Open Project dialog navigate to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/</tt> directory.</p></li>
<li><p>Select the <tt>writer</tt> folder.</p></li>
<li><p>Select the Open as Main Project check box.</p></li>
<li><p>Click Open Project.</p></li>
<li><p>In the Projects tab, right-click the <tt>writer</tt> project and select Properties. The Project Properties dialog is displayed.</p></li>
<li><p>Enter the following in the Arguments field:</p><pre><tt><b>-f dist/CursorWriter-Output</b></tt></pre></li>
<li><p>Click OK.</p></li>
<li><p>Right-click the <tt>writer</tt> project and select Run.</p></li></ol>


<a name="bnbhd"></a><h5>Building and Running the Writer Example Using Ant</h5>
<p>To compile and run the Writer example using Ant, in a terminal
window, go to the <tt></tt><i>tut-install</i><tt>/javaeetutorial5/examples/stax/writer/</tt> directory and type the following:</p><pre><tt><b>ant run-writer</b></tt></pre>
         </div>
         <div class="navigation">
             <a href="bnbfi.html"><img style="padding-right: 3px" src="graphics/leftButton.gif" border="0"></a>
             <a href="sjsaseej2eet.html"><img style="padding-right: 3px" src="graphics/upButton.gif" border="0"></a>
             <a href="bnbhe.html"><img style="padding-left: 3px" src="graphics/rightButton.gif" border="0"></a>
         </div>

         <div class="copyright">
      	    <p>The material in The Java&trade; EE 5 Tutorial is <a href='docinfo.html'>copyright</a>-protected and may not be published in other works without express written permission from Sun Microsystems.</p>
      	 </div>

      </td>
   </tr>
</tbody>
</table>
</body>
</html>

